package org.xjc.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.xjc.config.securitycomponent.CustomAuthorityDeserializer;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : XJC
 * @Description :用户表
 * @create : 2022/8/26 14:18
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SecurityUserEntity extends BaseEntity implements UserDetails {

    @Column(name = "USER_NAME",columnDefinition = "varchar2(64)")
    @TableField("USER_NAME")
    private String userName;

    @Column(name = "REAL_NAME",columnDefinition = "varchar2(64)")
    @TableField("REAL_NAME")
    private String realName;

    @Column(name = "PASSWORD",columnDefinition = "varchar2(64)")
    @TableField("PASSWORD")
    private String password;

    /**
     * 是否启用，0否1是
     */
    @Column(name = "ENABLED",columnDefinition = "number(1)")
    @TableField("ENABLED")
    private Integer enabled = 1;

    @Transient
    @TableField(exist = false)
    private List<RoleEntity> roles;

    @Override
    @JsonDeserialize(using = CustomAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleCode()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled == 1;
    }


}
